#include "workspace.h"

#include <iostream>
using namespace std;
#include <stdlib.h>
Workspace::Workspace()
{
}
//Workspace::Workspace(int N, int M){
//    width=N;
//    height=M;
//    //create cells of the workspace
//    for (int i =0; i<width;i++){
//        for (int j=0; j<height;j++){
//            cellMatrix[i][j]=new Cell(i,j);
//        }
//    }

//    Path* path1 = new Path();
//        path1->addCell(cellMatrix[0][4]);
//        path1->addCell(cellMatrix[1][4]);
//        path1->addCell(cellMatrix[2][4]);
//        path1->addCell(cellMatrix[3][4]);
//        path1->addCell(cellMatrix[3][3]);
//        path1->addCell(cellMatrix[3][2]);
//        path1->addCell(cellMatrix[3][1]);
//        path1->addCell(cellMatrix[3][0]);


//        //create 2 robots on the scene
//        Robot* robot1 = new Robot(1);
//        robots.push_back(robot1);
//        robot1->setPath(path1);


    //create paths from "text.xml"
//    XMLReader reader;
//    reader.run();
//    WorkspaceFactory::Instance().print();
//    this->robots = WorkspaceFactory::Instance().getRobots();
//std::cout<<"robotlist size="<<this->robots.size()<<endl;
//    std::cout<<"cells set"<<std::endl;
//}




bool Workspace::isNextStateSafe(Robot* robot){

    //need to check if the next state will be safe
    //after granting a resource (cell) access for the robot

    if (robot->path->first()->isGranted())
        return false;
    ssc = new SafeStateCheck(robot,robots);
    printStage();
    adjustPathCells(ssc);
    std::cout<<"after adjusting safety cells"<<std::endl;
    ssc->printSafetyCheckCells();
    std::cout<<"in isNextStateSafe for ";
    robot->printPath();
    return ssc->isNextStateSafe(robot);
}


void Workspace::adjustPathCells(SafeStateCheck * ssc){
   // std::cout<<"adjustPathCells:"<<std::endl;
    ssc->safetyCheckCells.clear();
    for(int i=0; i<this->width;i++){
        for(int j=0; j<this->height;j++){
            Cell* pCell = this->cellMatrix[i][j];
            if (pCell->isOnPath() || pCell->isGranted()){
                ssc->safetyCheckCells.push_back(new Cell(
                        pCell->x,pCell->y,pCell->getRobots(),pCell->getGrantedRobot()));
            }
        }
    }
   // std::cout<<"\nEND:adjustPathCells:"<<std::endl;
}

void Workspace::printSafetyCheckCells(){
    ssc->printSafetyCheckCells();
}

void Workspace::printStage(){
    std::cout<<endl;
    std::list<Robot*>::iterator robotIt;


    for(int i=0; i<this->width;i++){
        for(int j=0; j<this->height;j++){
            Cell* pCell = this->cellMatrix[i][j];
            pCell->printCell();
            std::cout << "\t";
        }
        std::cout<< endl;
    }
}
